import math
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta
import matplotlib.dates as mdates

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class ShowPassRate:
    def __init__(self):
        self.path = ''
        self.data = {}
        self.p85 = None

    def read_file(self, path):
        self.path = path
        self.get_data()
        self.show()
        self.clear()

    def show(self):
        # 提取数据
        keys = list(self.data.keys())
        # 将时间字符串转换为datetime对象
        times = [datetime.strptime(time, '%H:%M') for time in keys]
        percentage = [d['Percentage'] for d in self.data.values() if 'Percentage' in d]

        # 第一组
        plt.plot(times, percentage, marker='o', linestyle='-', color='r', label='通过率')
        # 绘制85分位数线
        plt.axhline(y=80, color='b', linestyle='--', label='80% Line')

        # 设置X轴为每1小时一个标记
        ax = plt.gca()  # 获取当前的Axes
        fig = ax.figure
        fig.set_size_inches(20, 12)  # 宽度为10英寸，高度为6英寸
        # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
        ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 60], interval=1))  # 每半小时一个主要刻度
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
        plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式

        # 添加标签和标题
        ax.set_xlabel('时间')
        ax.set_ylabel('通过率（%）')
        name = os.path.basename(self.path).split('_')[0]
        if name == 'car':
            ax.set_title('小客车通过率')
        else:
            ax.set_title('所有车型通过率')
        ax.legend(loc='lower right')

        # # 显示图表
        # plt.show()

        # 保存图表到文件
        output_dir = os.path.join(os.path.dirname(self.path), 'png')
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        file_name = os.path.basename(self.path).split('.')[0]
        output_filename = os.path.join(output_dir, file_name + '.png')
        plt.savefig(output_filename, dpi=200)
        # 关闭图表以释放内存
        plt.close()

    def get_data(self):
        df_up = pd.read_csv(self.path)
        data0 = df_up.to_dict(orient='records')
        # print(data0)
        self.data = {}
        for i in range(len(data0)):
            time = data0[i]['Group_Time'].split(' ')[1][:5]
            self.data[time] = {
                "Valid_Count": data0[i]['Valid_Count'],
                "Total_Count": data0[i]['Total_Count'],
                "Percentage": data0[i]['Percentage']
            }
        # print(self.data)

    def clear(self):
        self.data.clear()
        self.p85 = None
        self.path = ''


if __name__ == '__main__':

    name = "G004251002000620010,G004251001000320010-20240207"
    path0 = r'D:\GJ\项目\事故检测\output\邻垫高速'
    path = os.path.join(path0, name, 'all_pass_rate_data.csv')

    showPassRate = ShowPassRate()
    showPassRate.read_file(path)


